package redis

import (
	"errors"
	"gitee.com/go-web-2/web_framework/context"
)

type Session struct {
	cmd      redis.Cmdable
	redisKey string
	id       string
}

func (s *Session) Get(ctx *context.Context, id string) (interface{}, error) {
	return s.cmd.HGet(ctx.R.Context(), s.redisKey, id).Result()
}

func (s *Session) Set(ctx *context.Context, id string, data interface{}) error {
	var lua = `
if redis.call("exists", KEYS[1])
then
	redis.call("hset",KEYS[1],ARGV[1],ARGV[2])
else
	return -1
end
`
	res, err := s.cmd.Eval(ctx.R.Context(), lua, []string{s.redisKey}, id, data).Int()
	if err != nil && err.Error() != "redis: nil" {
		return err
	}
	if res < 0 {
		return errors.New("创建session失败")
	}
	return nil
}

func (s *Session) ID() string {
	return s.id
}
